from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_socketio import SocketIO
from celery import Celery
import redis
from config import config

# 初始化扩展
db = SQLAlchemy()
jwt = JWTManager()
socketio = SocketIO()
redis_client = None
celery = None

def create_app(config_name='default'):
    """应用工厂函数"""
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    jwt.init_app(app)
    CORS(app, origins="*")
    socketio.init_app(app, cors_allowed_origins="*")
    
    # 初始化Redis
    global redis_client
    redis_client = redis.from_url(app.config['REDIS_URL'])
    
    # 初始化Celery
    global celery
    celery = Celery(
        app.import_name,
        broker=app.config['CELERY_BROKER_URL'],
        backend=app.config['CELERY_RESULT_BACKEND']
    )
    celery.conf.update(app.config)
    
    # 注册蓝图
    from app.api import api_bp
    from app.web import web_bp
    from app.websocket import socketio_bp
    
    app.register_blueprint(api_bp, url_prefix='/api')
    app.register_blueprint(web_bp)
    app.register_blueprint(socketio_bp)
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    return app

def create_celery_app(app):
    """创建Celery应用"""
    celery = Celery(
        app.import_name,
        broker=app.config['CELERY_BROKER_URL'],
        backend=app.config['CELERY_RESULT_BACKEND']
    )
    celery.conf.update(app.config)
    
    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)
    
    celery.Task = ContextTask
    return celery
